<template>
  <div class="home-page">
    <!--  菜单栏  -->
    <div class="menu_bg">
      <div class="menu">
        <!-- 商品分类详情 -->
        <div class="nav">
          <div class="nav_t">全部商品分类</div>
          <div class="leftNav">
            <ul>
              <li v-for="(category, index) in categories" :key="category.id">
                <div class="fj">
                  <span class="n_img"><span></span><img :src="category.icon" :alt="category.name" /></span>
                  <span class="fl">{{ category.name }}</span>
                </div>
                <div class="zj" :style="{ top: -index * 40 + 'px' }">
                  <div class="zj_l">
                    <div class="zj_l_c" v-for="(subcategory, subIndex) in category.subcategories" :key="subIndex">
                      <h2>{{ subcategory.title }}</h2>
                      <template v-for="(item, itemIndex) in subcategory.items" :key="itemIndex">
                        <router-link :to="{ name: 'CategoryProducts', params: { id: item.id } }">{{ item.name }}</router-link>
                        <span v-if="itemIndex < subcategory.items.length - 1">|</span>
                      </template>
                    </div>
                  </div>
                  <div class="zj_r">
                    <a href="#" v-for="(image, imgIndex) in category.images" :key="imgIndex">
                      <img :src="image" width="236" height="200" :alt="`分类图片${imgIndex + 1}`" />
                    </a>
                  </div>
                </div>
              </li>
            </ul>
          </div>
        </div>
        <!--End 商品分类详情 End-->

        <ul class="menu_r">
          <li><router-link to="/">首页</router-link></li>
          <li><router-link :to="{ name: 'CategoryProducts', params: { id: 628 } }">美食</router-link></li>
          <li><router-link :to="{ name: 'CategoryProducts', params: { id: 660 } }">生鲜</router-link></li>
          <li><router-link :to="{ name: 'CategoryProducts', params: { id: 676 } }">家居</router-link></li>
          <li><router-link :to="{ name: 'CategoryProducts', params: { id: 548 } }">女装</router-link></li>
          <li><router-link :to="{ name: 'CategoryProducts', params: { id: 548 } }">美妆</router-link></li>
          <li><router-link :to="{ name: 'CategoryProducts', params: { id: 670 } }">数码</router-link></li>
          <li><router-link :to="{ name: 'ProductList' }">团购</router-link></li>
        </ul>
        <div class="m_ad">中秋送好礼！</div>
      </div>
    </div>
    <!--End Menu End-->
    
    <div class="i_bg bg_color">
      <div class="i_ban_bg">
        
        <!-- Banner轮播图 -->
        <BannerSlider />
        
        <!-- 新闻资讯 -->
        <NewsSection 
          :news-list="newsList" 
          @view-more="viewMoreNews" 
          @view-news="viewNews" 
          @recharge="handleRecharge" 
        />
      </div>
      
      <!-- 热门商品 -->
      <HotProducts :products="hotProducts" @view-product="viewProduct" />
      
      <!-- 限时特卖 -->
      <FlashSale 
        :banners="saleBanners" 
        :products="saleProducts" 
        @view-more="viewMoreSales" 
        @view-banner="viewBanner" 
        @view-product="viewProduct" 
      />
      
      <div class="content mar_20">
        <img src="@/assets/images/mban_1.jpg" width="1200" height="110" />
      </div>
      
      <!-- 商品楼层 -->
      <ProductFloor
        v-for="(floor, index) in productFloors"
        :key="floor.id"
        :floor-number="index + 1"
        :title="floor.title"
        :links="floor.links"
        :banners="floor.banners"
        :tags="floor.tags"
        :products="floor.products"
        :ads="floor.ads"
        :identifier="floor.identifier"
        @view-category="viewCategory"
        @view-banner="viewBanner"
        @view-tag="viewTag"
        @view-product="viewProduct"
        @view-ad="viewAd"
      />
      
      <!-- 猜你喜欢 -->
      <GuessYouLike :products="recommendedProducts" @view-product="viewProduct" />

    </div>
  </div>
</template>

<script>
import { getHotProducts, getSaleProducts, queryProduct, getProductCategories } from '@/api/productApi'
import { getLatestNews } from '@/api/newsApi'
import BannerSlider from '@/components/home/BannerSlider.vue'
import NewsSection from '@/components/home/NewsSection.vue'
import HotProducts from '@/components/home/HotProducts.vue'
import FlashSale from '@/components/home/FlashSale.vue'
import ProductFloor from '@/components/home/ProductFloor.vue'
import GuessYouLike from '@/components/home/GuessYouLike.vue'

export default {
  name: 'HomePage',
  components: {
    BannerSlider,
    NewsSection,
    HotProducts,
    FlashSale,
    ProductFloor,
    GuessYouLike
  },
  data() {
    return {
      // 搜索相关数据
      searchKeyword: '',
      
      // 购物车相关数据
      isLoggedIn: false,
      showCart: false,
      cartCount: 0,
      cartItems: [],
      
      // Banner数据
      banners: [],
      
      // 新闻资讯数据
      newsList: [],
      pagination: {
        total: 0
      },
      
      // 热门商品数据
      hotProducts: [],
      
      // 限时特卖数据
      saleBanners: [],
      saleProducts: [],
      
      // 商品分类数据
      categories: [],
      
      // 商品楼层数据
      productFloors: [],
      
      // 推荐商品数据
      recommendedProducts: [],
      userId: ''
    }
  },
  // 计算属性
  computed: {
    // 计算购物车总价格
    totalPrice() {
      return this.cartItems.reduce((total, item) => {
        return total + (item.price * item.quantity)
      }, 0)
    }
  },
  // 组件挂载后执行
  async mounted() {
    // 检查登录状态
    this.checkLoginStatus()
    // 初始化购物车数据
    this.loadCartData()
    
    // 加载所有主页数据
    await this.loadAllData()
    
    // 组件挂载后执行，初始化轮播图等功能
    console.log('HomePage 组件已加载')
    this.$nextTick(() => {
      setTimeout(() => {
        this.initSlider()
        this.initNavigation()
        this.initHoverEffects()
      }, 100)
    })
  },
  // 组件销毁前执行
  beforeUnmount() {
    // 组件销毁前清理工作
    this._isDestroyed = true
    // 清理定时器等
  },
  // 方法
  methods: {
    // 加载所有主页数据
    async loadAllData() {
      try {
        // 并行加载所有数据
        await Promise.all([
          this.loadNewsData(),
          this.loadHotProductsData(),
          this.loadSaleProductsData(),
          this.loadCategoryProductsData(),
          this.loadRecommendedProductsData(),
          this.loadBannerData(),
          this.loadCategoryData()
        ])
      } catch (error) {
        console.error('加载主页数据失败:', error)
        this.$message.error('数据加载失败，请稍后重试')
      }
    },
    
    // 加载新闻资讯数据
    async loadNewsData() {
      try {
        // 获取最新的5条新闻
        const newsListRes = await getLatestNews()
        console.log('latest news query res:', newsListRes)
        
        // 处理后端返回的新闻数据
        if (newsListRes) {
          // 如果res是数组，直接使用
          if (Array.isArray(newsListRes)) {
            this.newsList = newsListRes.map(item => ({
              ...item,
              // 确保createTime正确显示
              createTime: item.createTime || ''
            }))
            this.pagination.total = newsListRes.length
          } 
          // 如果res包含data字段
          else if (newsListRes.data) {
            // 如果data是数组，直接使用
            if (Array.isArray(newsListRes.data)) {
              this.newsList = newsListRes.data.map(item => ({
                ...item,
                // 确保createTime正确显示
                createTime: item.createTime || ''
              }))
              this.pagination.total = newsListRes.total || newsListRes.data.length
            } 
            // 其他情况
            else {
              this.newsList = []
              this.pagination.total = 0
            }
          } 
          // 其他情况
          else {
            this.newsList = []
            this.pagination.total = 0
          }
        } else {
          this.newsList = []
          this.pagination.total = 0
        }
      } catch (error) {
        console.error('加载新闻数据失败:', error)
        this.$message.error('新闻数据加载失败: ' + (error.message || '未知错误'))
        this.newsList = []
        this.pagination.total = 0
      }
    },
    
    // 加载热门商品数据
    async loadHotProductsData() {
      try {
        // 使用queryProduct获取热门商品数据，不指定分类ID以获取所有商品
        const hotProductsRes = await queryProduct({ pageSize: 999 })
        this.hotProducts = hotProductsRes.data || []
        this.recommendedProducts = hotProductsRes.data || []
      } catch (error) {
        console.error('加载热门商品数据失败:', error)
        this.$message.error('热门商品数据加载失败')
      }
    },
    
    // 加载限时特卖数据
    async loadSaleProductsData() {
      try {
        // 使用queryProduct获取特卖商品数据
        const saleProductsRes = await queryProduct({ pageSize: 999 })
        this.saleProducts = saleProductsRes.data || []
        // 对于横幅广告，使用默认图片
        this.saleBanners = [
          { id: 1, image: require('@/assets/images/nban.jpg'), title: '特卖广告1' },
          { id: 2, image: require('@/assets/images/tm_ban.jpg'), title: '特卖广告2' }
        ]
      } catch (error) {
        console.error('加载限时特卖数据失败:', error)
        this.$message.error('限时特卖数据加载失败')
      }
    },
    
    // 加载各类别商品数据
    async loadCategoryProductsData() {
      try {
        // 先获取所有分类数据
        const categoryRes = await getProductCategories()
        let categoriesData = []
        if (categoryRes && categoryRes.data) {
          categoriesData = Array.isArray(categoryRes.data) ? categoryRes.data : [] 
          // console.log('A-分类数据:', categoriesData)
        } else if (Array.isArray(categoryRes)) {
          categoriesData = categoryRes  // 如果返回的是数组，则直接使用
          // console.log('B-分类数据:', categoriesData) 
        }
        
        // 构建分类树结构
        const level1Categories = categoriesData.filter(cat => cat.parentId === '0')
        const level2Categories = categoriesData.filter(cat => cat.parentId !== '0' && cat.type === 2)
        const level3Categories = categoriesData.filter(cat => cat.parentId !== '0' && cat.type === 3)
        
        // 根据实际获取的一级分类数量来构建楼层配置
        const floorConfigs = level1Categories.map((level1Cat, index) => {
          // 获取该一级分类下的二级分类
          const subcategories = level2Categories.filter(cat => cat.parentId === level1Cat.id)
          
          // 构建二级和三级分类的链接结构
          let links = []
          subcategories.forEach((subcategory, subIndex) => {
            // 为每个二级分类添加一个链接
            links.push({
              id: subcategory.id,
              name: subcategory.name
            })
            
            // 获取该二级分类下的三级分类
            const thirdCategories = level3Categories.filter(cat => cat.parentId === subcategory.id)
            // 为前几个三级分类也添加链接（最多3个）
            thirdCategories.slice(0, 3).forEach((thirdCategory, thirdIndex) => {
              links.push({
                id: thirdCategory.id,
                name: thirdCategory.name
              })
            })
          })
          
          // 如果链接数量不足5个，用默认链接补充
          if (links.length < 5) {
            const defaultLinks = [
              { id: 1, name: '热门商品' },
              { id: 2, name: '新品推荐' },
              { id: 3, name: '特价商品' },
              { id: 4, name: '畅销商品' },
              { id: 5, name: '限时抢购' }
            ]
            links = [...links, ...defaultLinks.slice(0, 5 - links.length)]
          }
          
          // 如果链接数量超过5个，只保留前5个
          if (links.length > 5) {
            links = links.slice(0, 5)
          }
          
          // 生成标签（从二级和三级分类中提取）
          let tags = []
          subcategories.forEach(subcategory => {
            // 为每个二级分类添加标签
            tags.push({
              id: subcategory.id,
              name: subcategory.name.length > 5 ? subcategory.name.substring(0, 5) : subcategory.name
            })
            
            // 获取该二级分类下的三级分类
            const thirdCategories = level3Categories.filter(cat => cat.parentId === subcategory.id)
            // 为三级分类添加标签
            thirdCategories.forEach(thirdCategory => {
              tags.push({
                id: thirdCategory.id,
                name: thirdCategory.name.length > 5 ? thirdCategory.name.substring(0, 5) : thirdCategory.name
              })
            })
          })
          
          // 如果标签数量不足9个，用默认标签补充
          if (tags.length < 9) {
            const defaultTags = [
              { id: 1, name: '热销' },
              { id: 2, name: '新品' },
              { id: 3, name: '特价' },
              { id: 4, name: '推荐' },
              { id: 5, name: '限时' },
              { id: 6, name: '爆款' },
              { id: 7, name: '精选' },
              { id: 8, name: '人气' },
              { id: 9, name: '优质' }
            ]
            tags = [...tags, ...defaultTags.slice(0, 9 - tags.length)]
          }
          
          // 如果标签数量超过9个，只保留前9个
          if (tags.length > 9) {
            tags = tags.slice(0, 9)
          }
          
          return {
            id: index + 1,
            title: level1Cat.name,
            identifier: `category_${level1Cat.id}`,
            categoryId: level1Cat.id,
            subcategories: subcategories,
            links: links,
            tags: tags
          }
        })
        
        // 为每个楼层获取商品数据
        const productFloorsData = []
        // console.log('C-楼层配置:', floorConfigs)
        
        // 跟踪已使用的商品ID，确保不同楼层显示不同的商品
        const usedProductIds = new Set();
        
        for (let i = 0; i < floorConfigs.length; i++) {
          const config = floorConfigs[i]
          
          // 实时加载该一级分类下的商品（限制为6个）
          let selectedProducts = []
          try {
            // 获取该一级分类下的所有商品
            const allCategoryProductsRes = await queryProduct({ categoryId: config.categoryId, pageSize: 100 });
            let allCategoryProducts = [];
            if (allCategoryProductsRes && allCategoryProductsRes.data) {
              allCategoryProducts = Array.isArray(allCategoryProductsRes.data) ? allCategoryProductsRes.data : [];
            } else if (Array.isArray(allCategoryProductsRes)) {
              allCategoryProducts = allCategoryProductsRes;
            }
            
            // 过滤掉已经使用的商品
            const filteredCategoryProducts = allCategoryProducts.filter(product => !usedProductIds.has(product.id));
            
            // 取前6个商品
            selectedProducts = filteredCategoryProducts.slice(0, 6);
            console.log(`C-一级分类${config.title}下的商品:`, selectedProducts)
            
            // 如果该分类下商品不足6个，记录实际数量
            if (selectedProducts.length < 6) {
              console.log(`分类${config.title}下商品不足6个，实际数量: ${selectedProducts.length}`);
            }
            
            // 记录已使用的商品ID
            selectedProducts.forEach(product => usedProductIds.add(product.id));
            
            // 构建楼层数据
            const floorData = {
              id: config.id,
              title: config.title,
              identifier: config.identifier,
              links: config.links,
              banners: [],
              tags: config.tags,
              products: selectedProducts, // 确保只显示该分类下的商品
              ads: []
            }
            console.log('D-最终的楼层数据:', this.productFloors);
            
            // 设置楼层特定的图片
            switch(config.title) {
              case '化妆品':
                floorData.banners = [
                  { id: 1, image: require('@/assets/images/make_r.jpg'), title: '轮播图1' },
                  { id: 2, image: require('@/assets/images/make_r.jpg'), title: '轮播图2' },
                  { id: 3, image: require('@/assets/images/make_r.jpg'), title: '轮播图3' }
                ]
                floorData.ads = [
                  { id: 1, image: require('@/assets/images/make_b1.jpg'), width: 260, height: 220, title: '广告1' },
                  { id: 2, image: require('@/assets/images/make_b2.jpg'), width: 260, height: 220, title: '广告2' }
                ]
                break
              case '家用商品':
                floorData.banners = [
                  { id: 1, image: require('@/assets/images/home_r.jpg'), title: '轮播图1' },
                  { id: 2, image: require('@/assets/images/home_r.jpg'), title: '轮播图2' },
                  { id: 3, image: require('@/assets/images/home_r.jpg'), title: '轮播图3' }
                ]
                floorData.ads = [
                  { id: 1, image: require('@/assets/images/home_b1.jpg'), width: 260, height: 220, title: '广告1' },
                  { id: 2, image: require('@/assets/images/home_b2.jpg'), width: 260, height: 220, title: '广告2' }
                ]
                break
              case '进口食品、生鲜':
                floorData.banners = [
                  { id: 1, image: require('@/assets/images/fre_r.jpg'), title: '轮播图1' },
                  { id: 2, image: require('@/assets/images/fre_r.jpg'), title: '轮播图2' },
                  { id: 3, image: require('@/assets/images/fre_r.jpg'), title: '轮播图3' }
                ]
                floorData.ads = [
                  { id: 1, image: require('@/assets/images/fre_b1.jpg'), width: 260, height: 220, title: '广告1' },
                  { id: 2, image: require('@/assets/images/fre_b2.jpg'), width: 260, height: 220, title: '广告2' }
                ]
                break
              case '电子商品':
                floorData.banners = [
                  { id: 1, image: require('@/assets/images/tel_r.jpg'), title: '轮播图1' },
                  { id: 2, image: require('@/assets/images/tel_r.jpg'), title: '轮播图2' },
                  { id: 3, image: require('@/assets/images/tel_r.jpg'), title: '轮播图3' }
                ]
                floorData.ads = [
                  { id: 1, image: require('@/assets/images/tel_b1.jpg'), width: 260, height: 220, title: '广告1' },
                  { id: 2, image: require('@/assets/images/tel_b2.jpg'), width: 260, height: 220, title: '广告2' }
                ]
                break
              case '保健食品':
                floorData.banners = [
                  { id: 1, image: require('@/assets/images/food_r.jpg'), title: '轮播图1' },
                  { id: 2, image: require('@/assets/images/food_r.jpg'), title: '轮播图2' },
                  { id: 3, image: require('@/assets/images/food_r.jpg'), title: '轮播图3' }
                ]
                floorData.ads = [
                  { id: 1, image: require('@/assets/images/food_b1.jpg'), width: 260, height: 220, title: '广告1' },
                  { id: 2, image: require('@/assets/images/food_b2.jpg'), width: 260, height: 220, title: '广告2' }
                ]
                break
              case '箱包':
                floorData.banners = [
                  { id: 1, image: require('@/assets/images/fre_r.jpg'), title: '轮播图1' }, // 使用生鲜图片作为默认
                  { id: 2, image: require('@/assets/images/fre_r.jpg'), title: '轮播图2' },
                  { id: 3, image: require('@/assets/images/fre_r.jpg'), title: '轮播图3' }
                ]
                floorData.ads = [
                  { id: 1, image: require('@/assets/images/fre_b1.jpg'), width: 260, height: 220, title: '广告1' }, // 使用生鲜广告作为默认
                  { id: 2, image: require('@/assets/images/fre_b2.jpg'), width: 260, height: 220, title: '广告2' }
                ]
                break
              default:
                floorData.banners = [
                  { id: 1, image: require('@/assets/images/fre_r.jpg'), title: '轮播图1' }, // 使用生鲜图片作为默认
                  { id: 2, image: require('@/assets/images/fre_r.jpg'), title: '轮播图2' },
                  { id: 3, image: require('@/assets/images/fre_r.jpg'), title: '轮播图3' }
                ]
                floorData.ads = [
                  { id: 1, image: require('@/assets/images/fre_b1.jpg'), width: 260, height: 220, title: '广告1' }, // 使用生鲜广告作为默认
                  { id: 2, image: require('@/assets/images/fre_b2.jpg'), width: 260, height: 220, title: '广告2' }
                ]
            }
            
            productFloorsData.push(floorData);
          } catch (error) {
            console.error(`加载楼层${config.title}商品数据失败:`, error);
            // 如果加载失败，使用空的商品数组
            const floorData = {
              id: config.id,
              title: config.title,
              identifier: config.identifier,
              links: config.links,
              banners: [],
              tags: config.tags,
              products: [], // 空的商品数组
              ads: []
            }
            
            // 设置默认图片
            floorData.banners = [
              { id: 1, image: require('@/assets/images/fre_r.jpg'), title: '轮播图1' },
              { id: 2, image: require('@/assets/images/fre_r.jpg'), title: '轮播图2' },
              { id: 3, image: require('@/assets/images/fre_r.jpg'), title: '轮播图3' }
            ]
            floorData.ads = [
              { id: 1, image: require('@/assets/images/fre_b1.jpg'), width: 260, height: 220, title: '广告1' },
              { id: 2, image: require('@/assets/images/fre_b2.jpg'), width: 260, height: 220, title: '广告2' }
            ]
            
            productFloorsData.push(floorData);
          }
        }
        
        this.productFloors = productFloorsData;
      } catch (error) {
        console.error('加载分类商品数据失败:', error);
        this.$message.error('分类商品数据加载失败');
      }
    },
    
    // 加载推荐商品数据
    async loadRecommendedProductsData() {
      try {
        // 使用queryProduct获取推荐商品数据，不指定分类ID以获取所有商品
        const recommendedProductsRes = await queryProduct({ pageSize: 12 })
        this.recommendedProducts = recommendedProductsRes.data || []
      } catch (error) {
        console.error('加载推荐商品数据失败:', error)
        this.$message.error('推荐商品数据加载失败')
        this.recommendedProducts = []
      }
    },
    
    // 加载Banner数据
    loadBannerData() {
      // 加载Banner数据（这些可能需要额外的API）
      this.banners = [
        { id: 1, title: '夏季大促销', image: '@/assets/images/ban1.jpg' },
        { id: 2, title: '新品上市', image: '@/assets/images/nban.jpg' },
        { id: 3, title: '品质生活', image: '@/assets/images/tm_ban.jpg' },
        { id: 4, title: '牛奶促销', image: '@/assets/images/milk_ban.jpg' }
      ]
    },
    
    // 加载商品分类数据
    async loadCategoryData() {
      try {
        // 从数据库获取商品分类数据
        const categoryRes = await getProductCategories()
        console.log('获取到的分类数据:', categoryRes)
        
        // 检查响应结构
        let categoriesData = []
        if (categoryRes && categoryRes.data) {
          categoriesData = Array.isArray(categoryRes.data) ? categoryRes.data : []
        } else if (Array.isArray(categoryRes)) {
          categoriesData = categoryRes
        }
        
        console.log('处理后的分类数据:', categoriesData)
        
        // 检查数据结构
        if (categoriesData.length > 0) {
          console.log('第一个分类数据示例:', categoriesData[0])
        }
        
        // 构建分类树结构
        // 注意：后端返回的parentId是字符串类型，type是Integer类型
        const level1Categories = categoriesData.filter(cat => cat.parentId === '0')
        const level2Categories = categoriesData.filter(cat => cat.parentId !== '0' && cat.type === 2)
        const level3Categories = categoriesData.filter(cat => cat.parentId !== '0' && cat.type === 3)
        
        console.log('一级分类:', level1Categories)
        console.log('二级分类:', level2Categories)
        console.log('三级分类:', level3Categories)
        
        // 构建最终的分类数据结构
        this.categories = level1Categories.map(level1 => {
          // 查找当前一级分类下的所有二级分类
          const subcategories = level2Categories
            .filter(level2 => level2.parentId === level1.id)
            .map(level2 => {
              // 查找当前二级分类下的所有三级分类
              const items = level3Categories
                .filter(level3 => level3.parentId === level2.id)
                .map(level3 => ({
                  id: level3.id,
                  name: level3.name
                }))
              
              return {
                title: level2.name,
                items: items
              }
            })
          
          // 根据一级分类ID分配图标和图片
          let icon, images
          switch(level1.id) {
            case 548: // 化妆品
              icon = require('@/assets/images/nav3.png')
              images = [require('@/assets/images/make_1.jpg'), require('@/assets/images/make_2.jpg')]
              break
            case 628: // 家用商品
              icon = require('@/assets/images/nav4.png')
              images = [require('@/assets/images/home_1.jpg'), require('@/assets/images/home_2.jpg')]
              break
            case 660: // 进口食品、生鲜
              icon = require('@/assets/images/nav1.png')
              images = [require('@/assets/images/n_img1.jpg'), require('@/assets/images/n_img2.jpg')]
              break
            case 670: // 电子商品
              icon = require('@/assets/images/nav5.png')
              images = [require('@/assets/images/tel_1.jpg'), require('@/assets/images/tel_2.jpg')]
              break
            case 676: // 保健食品
              icon = require('@/assets/images/nav6.png')
              images = [require('@/assets/images/baby_1.jpg'), require('@/assets/images/baby_2.jpg')]
              break
            case 681: // 箱包
              icon = require('@/assets/images/nav2.png')
              images = [require('@/assets/images/food_1.jpg'), require('@/assets/images/food_2.jpg')]
              break
            default:
              icon = require('@/assets/images/nav1.png')
              images = [require('@/assets/images/n_img1.jpg'), require('@/assets/images/n_img2.jpg')]
          }
          
          return {
            id: level1.id,
            name: level1.name,
            icon: icon,
            subcategories: subcategories,
            images: images
          }
        })
        
        console.log('最终构建的分类数据:', this.categories)
      } catch (error) {
        console.error('加载商品分类数据失败:', error)
        this.$message.error('商品分类数据加载失败')
        // 如果加载失败，使用默认数据
        this.categories = [
          {
            id: 548,
            name: '化妆品',
            icon: require('@/assets/images/nav3.png'),
            subcategories: [
              {
                title: '面部护理',
                items: [
                  { id: 655, name: '少女派' }
                ]
              }
            ],
            images: [require('@/assets/images/make_1.jpg'), require('@/assets/images/make_2.jpg')]
          },
          {
            id: 628,
            name: '家用商品',
            icon: require('@/assets/images/nav4.png'),
            subcategories: [
              {
                title: '餐具',
                items: [
                  { id: 658, name: '叉子' },
                  { id: 659, name: '锅' },
                  { id: 692, name: '刀叉' },
                  { id: 693, name: '碗筷' }
                ]
              },
              {
                title: '卫具',
                items: [
                  { id: 700, name: '马桶' }
                ]
              },
              {
                title: '客厅专用',
                items: [
                  { id: 701, name: '沙发' },
                  { id: 702, name: '收纳用品' },
                  { id: 703, name: '清洁用品' },
                  { id: 711, name: '婴儿用品' }
                ]
              }
            ],
            images: [require('@/assets/images/home_1.jpg'), require('@/assets/images/home_2.jpg')]
          },
          {
            id: 660,
            name: '进口食品、生鲜',
            icon: require('@/assets/images/nav1.png'),
            subcategories: [
              {
                title: '零食/糖果/巧克力',
                items: [
                  { id: 662, name: '坚果' },
                  { id: 663, name: '蜜饯' }
                ]
              }
            ],
            images: [require('@/assets/images/n_img1.jpg'), require('@/assets/images/n_img2.jpg')]
          },
          {
            id: 670,
            name: '电子商品',
            icon: require('@/assets/images/nav5.png'),
            subcategories: [
              {
                title: '手机',
                items: [
                  { id: 672, name: '华为手机' },
                  { id: 673, name: '联想手机' }
                ]
              },
              {
                title: '手环',
                items: [
                  { id: 675, name: '小米手环' }
                ]
              },
              {
                title: '电脑',
                items: [
                  { id: 691, name: '联想电脑' }
                ]
              }
            ],
            images: [require('@/assets/images/tel_1.jpg'), require('@/assets/images/tel_2.jpg')]
          },
          {
            id: 676,
            name: '保健食品',
            icon: require('@/assets/images/nav6.png'),
            subcategories: [
              {
                title: '老年保健品',
                items: [
                  { id: 680, name: '脑白金' }
                ]
              },
              {
                title: '中年营养品',
                items: [
                  { id: 704, name: '中年维生素' }
                ]
              },
              {
                title: '儿童保健品',
                items: [
                  { id: 705, name: '儿童奶粉' },
                  { id: 706, name: '儿童营养品' }
                ]
              }
            ],
            images: [require('@/assets/images/baby_1.jpg'), require('@/assets/images/baby_2.jpg')]
          },
          {
            id: 681,
            name: '箱包',
            icon: require('@/assets/images/nav2.png'),
            subcategories: [
              {
                title: '旅行箱',
                items: [
                  { id: 687, name: '大型旅行箱' },
                  { id: 688, name: '中型旅行箱' },
                  { id: 689, name: '小型旅行箱' },
                  { id: 709, name: '婴儿推车' }
                ]
              },
              {
                title: '手提箱',
                items: [
                  { id: 684, name: '大型手提箱' },
                  { id: 686, name: '中型手提箱' },
                  { id: 685, name: '小型手提箱' }
                ]
              }
            ],
            images: [require('@/assets/images/food_1.jpg'), require('@/assets/images/food_2.jpg')]
          }
        ]
      }
    },
    
    // 搜索相关方法
    handleSearch() {
      if (!this.searchKeyword.trim()) {
        this.$message.warning('请输入搜索关键字')
        return
      }
      this.$router.push({
        name: 'SearchResults',
        query: { keyword: this.searchKeyword }
      })
    },
    
    searchFor(keyword) {
      this.searchKeyword = keyword
      this.handleSearch()
    },
    
    // 购物车相关方法
    toggleCart() {
      this.showCart = !this.showCart
    },
    
    checkLoginStatus() {
      const userInfo = localStorage.getItem('userInfo')
      this.isLoggedIn = !!userInfo
      if (userInfo) {
        try {
          const user = JSON.parse(userInfo)
          this.username = user.name || ''
          this.userType = user.type || 0
          this.userId = user.id || '' // 获取用户ID
        } catch (e) {
          console.error('解析用户信息失败:', e)
          localStorage.removeItem('userInfo')
        }
      }
    },
    
    // 登录相关方法
    loadCartData() {
      if (this.isLoggedIn) {
        // 实际项目中应该从后端获取购物车数据
        this.cartItems = [
          {
            id: 1,
            name: '法颂浪漫梦境50ML 香水女士持久清新淡香 送2ML小样3只',
            price: 399,
            quantity: 1,
            image: '@/assets/images/car1.jpg'
          }
        ]
        this.cartCount = this.cartItems.length
      } else {
        this.cartItems = []
        this.cartCount = 0
      }
    },
    
    // 初始化轮播图
    initSlider() {
      console.log('开始初始化所有轮播图...')
    },
    
    // 初始化导航悬停效果
    initNavigation() {
      console.log('初始化导航悬停效果')
      // 添加悬停效果
      const leftNavItems = document.querySelectorAll('.leftNav ul li')
      leftNavItems.forEach(item => {
        item.addEventListener('mouseenter', function() {
          this.querySelector('.fj').classList.add('nuw')
          this.querySelector('.zj').style.display = 'block'
        })
        item.addEventListener('mouseleave', function() {
          this.querySelector('.fj').classList.remove('nuw')
          this.querySelector('.zj').style.display = 'none'
        })
      })
    },
    
    // 初始化悬停效果
    initHoverEffects() {
      console.log('初始化悬停效果')
      // 确保在DOM更新后再初始化
      this.$nextTick(() => {
        this.initNavigation()
      })
    },
    
    // 跳转到商品分类页面
    viewCategory(categoryId) {
      this.$router.push({ name: 'CategoryProducts', params: { id: categoryId } })
    },
    
    // 跳转到商品详情页面
    viewProduct(productId) {
      this.$router.push({ name: 'ProductDetail', params: { id: productId } })
    },
    
    // 查看Banner
    viewBanner(bannerId) {
      console.log('查看Banner:', bannerId)
    },
    
    // 查看标签
    viewTag(tagId) {
      console.log('查看标签:', tagId)
    },
    
    // 查看广告
    viewAd(adId) {
      console.log('查看广告:', adId)
    },
    
    // 添加到购物车
    addToCart(product) {
      this.$emit('add-to-cart', product)
      this.$message.success('商品已加入购物车')
    },
    
    // 话费充值
    handleRecharge(rechargeForm) {
      this.$message.success(`正在为 ${rechargeForm.phoneNumber} 充值 ${rechargeForm.amount}元...`)
    },
    
    // 查看更多新闻
    viewMoreNews() {
      this.$router.push('/news')
    },
    
    // 查看新闻详情
    viewNews(newsId) {
      this.$router.push(`/news/${newsId}`)
    },
    
    // 查看更多特卖
    viewMoreSales() {
      this.$router.push('/sales')
    }
  }
}
</script>

<style>
/* 引入主要样式文件 */
@import '@/assets/css/easybuy-style.css';

/* 首页特定样式 */
.home-page {
  min-height: 100vh;
}

/* 主头部区域 - 符合整体页面布局规范 */
.top {
  width: 1200px;
  height: 140px;
  margin: 0 auto;
  position: relative;
}

/* 其他样式保持不变 */
</style>
